//
//  WHFJMessageHelper.m
//  HelloCordova
//
//  Created by wanghongfei2016 on 16/8/22.
//
//

#import "WHFJMessageHelper.h"
#import "JCHATConversationListViewController.h"
#import <JMessage/JMSGUser.h>
#import <Cordova/CDV.h>
#import "JChatConstants.h"
#import "JCHATAlertViewWait.h"
#import "MBProgressHUD+Add.h"
#import <JMessage/JMSGUser.h>

@interface WHFJMessageHelper ()
{
    __block NSMutableArray *_conversationArr;
    UIButton *_rightBarButton;
    NSInteger _unreadCount;
    UILabel *_titleLabel;
}

@property (nonatomic, strong)NSString *callbackID;



@end

@implementation WHFJMessageHelper

-(void)test:(CDVInvokedUrlCommand *)command{
    
    __weak WHFJMessageHelper *weakSelf = self;
    
    
    
    
    NSString *username = [command.arguments objectAtIndex:0];
    //    NSString *nickname = [command.arguments objectAtIndex:1];
    NSLog(@"传递过来的名字是%@",username);
    [self presentToConversationList];
    /*
     //    [JMSGUser loginWithUsername:username   password:username completionHandler:^(id resultObject, NSError *error) {
     //
     //        if (error == nil) {
     //            NSLog(@">>>>><<<<<<<<result = %@",resultObject);
     //
     //            JCHATConversationListViewController *converListVC = [[JCHATConversationListViewController alloc]init];
     //
     //
     //            ChatConversationListViewController *chatVC = [[ChatConversationListViewController alloc]init];
     //            UINavigationController *chatNV = [[UINavigationController alloc]initWithRootViewController:converListVC];
     //            chatNV.navigationBar.translucent = NO;
     //
     //            [chatNV.navigationBar setBarTintColor:[UIColor blackColor]];
     //            [chatNV.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, nil]];
     //
     //            [weakSelf.viewController presentViewController:chatNV animated:YES completion:nil];
     //
     //        }else
     //        {
     //            NSString *errorString = [NSString stringWithFormat:@"%@",error];
     //
     //            NSString *codeString = [errorString substringWithRange:NSMakeRange(29, 6)];
     //            if ([codeString isEqualToString:@"863006"]) {
     //                JMSGUser *user = [JMSGUser myInfo];
     //                if ([user.username isEqualToString:username]) {
     //                    dispatch_async(dispatch_get_main_queue(), ^{
     //                        [weakSelf presentToConversationList];
     //
     //                    });
     //                }
     //                else
     //                {
     //                    [JMSGUser logout:^(id resultObject, NSError *error) {
     //                        if (error == nil) {
     //
     //                            [JMSGUser loginWithUsername:username password:username completionHandler:^(id resultObject, NSError *error) {
     //
     //                                if (error == nil) {
     //                                    [weakSelf presentToConversationList];
     //                                }else
     //                                {
     //                                    NSString *errerStr = [NSString stringWithFormat:@"%@",error];
     //                                    NSString *codeStr = [errerStr substringWithRange:NSMakeRange(29, 6)];
     //                                    if ([codeStr isEqualToString:@"801003"]) {
     //
     //                                        [JMSGUser registerWithUsername:username password:username completionHandler:^(id resultObject, NSError *error) {
     //                                            if (error == nil) {
     //
     //
     //                                                dispatch_async(dispatch_get_main_queue(), ^{
     //
     //                                                    [JMSGUser loginWithUsername:username password:username completionHandler:^(id resultObject, NSError *error) {
     //                                                        if (error == nil) {
     //                                                            [weakSelf presentToConversationList];
     //                                                        }
     //
     //                                                    }];
     //
     //
     //                                                });
     //
     //                                            }
     //
     //
     //                                        }];
     //
     //                                    }
     //
     //                                }
     //
     //                            }];
     //                        }
     //
     //                    }];
     //
     //                }
     //
     //            }else if ([codeString isEqualToString:@"801003"])
     //            {
     //                dispatch_async(dispatch_get_main_queue(), ^{
     //                    [JMSGUser registerWithUsername:username password:username completionHandler:^(id resultObject, NSError *error) {
     //                        if (error == nil) {
     //
     //
     //                            dispatch_async(dispatch_get_main_queue(), ^{
     //
     //                                [JMSGUser loginWithUsername:username password:username completionHandler:^(id resultObject, NSError *error) {
     //                                    if (error == nil) {
     //                                        [weakSelf presentToConversationList];
     //                                    }
     //
     //                                }];
     //
     //
     //                            });
     //
     //                        }
     //
     //
     //                    }];
     //
     //                });
     //
     //
     //
     //            }
     //
     //            NSLog(@"*********错误信息error = %@",error);
     //            NSLog(@">>>>>>------errorString = %@",[errorString substringWithRange:NSMakeRange(29, 6)]);
     //
     //            //
     //        }
     //
     //    }];
     //
     //
     //
     //
     //
     //    JCHATConversationListViewController *converListVC = [[JCHATConversationListViewController alloc]init];
     //
     //
     //    ChatConversationListViewController *chatVC = [[ChatConversationListViewController alloc]init];
     //    UINavigationController *chatNV = [[UINavigationController alloc]initWithRootViewController:converListVC];
     //    chatNV.navigationBar.translucent = NO;
     //
     //    [chatNV.navigationBar setBarTintColor:[UIColor blackColor]];
     //    [chatNV.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, nil]];
     
     //    [self.viewController presentViewController:chatNV animated:YES completion:nil];
     
     */
}

-(void)presentToConversationList
{
    
    JCHATConversationListViewController *converListVC = [[JCHATConversationListViewController alloc]init];
    UINavigationController *chatNV = [[UINavigationController alloc]initWithRootViewController:converListVC];
    chatNV.navigationBar.translucent = NO;
    
    [chatNV.navigationBar setBarTintColor:[UIColor blackColor]];
    [chatNV.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, nil]];
    
    [self.viewController presentViewController:chatNV animated:YES completion:nil];
    
    
}



-(void)login:(CDVInvokedUrlCommand *)command
{
    
    NSString *username = [command.arguments objectAtIndex:0];
    NSString *code = [command.arguments objectAtIndex:1];
    NSLog(@"登录的用户名 username = %@ ;密码 code = %@",username,code);
    [JMSGUser loginWithUsername:username password:code completionHandler:^(id resultObject, NSError *error) {
        
        if (error == nil) {
            //            [self alertWithTitle:@"登录成功"];
            NSLog(@">>>>>>>>>登录成功");
            
        }else
        {
            //            [self alertWithTitle:@"登录失败"];
            NSLog(@"登录失败error = %@",error);
        }
    }];
    
}

-(void)regist:(CDVInvokedUrlCommand *)command
{
    
    NSString *username = [command.arguments objectAtIndex:0];
    NSString *code = [command.arguments objectAtIndex:1];
    
    [JMSGUser registerWithUsername:username password:code completionHandler:^(id resultObject, NSError *error) {
        
        if (error == nil) {
            //            [self alertWithTitle:@"注册成功"];
            NSLog(@"注册成功");
        }else
        {
            //            [self alertWithTitle:@"注册失败"];
            NSLog(@"注册失败 error = %@",error);
        }
        
    }];
    
}

-(void)logout:(CDVInvokedUrlCommand *)command
{
    [JMSGUser logout:^(id resultObject, NSError *error) {
        
        if (error == nil) {
            //            [self alertWithTitle:@"退出了聊天服务器"];
            NSLog(@"退出了聊天服务器");
            
        }else
        {
            //            [self alertWithTitle:@"退出了聊天服务器失败"];
            NSLog(@"退出了聊天服务器失败");
            
        }
    }];
    
}



-(void)getAllConversationList:(CDVInvokedUrlCommand *)command
{
    
    
    NSInteger state = [[command.arguments objectAtIndex:0] integerValue];
    if (state == 0) {
        [self presentToConversationList];
        
    }
    else
    {
        [JMSGConversation allConversations:^(id resultObject, NSError *error) {
            JCHATMAINTHREAD(^{
                if (error == nil) {
                    _conversationArr = [self sortConversation:resultObject];
                    _unreadCount = 0;
                    for (NSInteger i=0; i < [_conversationArr count]; i++) {
                        JMSGConversation *conversation = [_conversationArr objectAtIndex:i];
                        _unreadCount = _unreadCount + [conversation.unreadCount integerValue];
                    }
                    
                    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)_unreadCount];
                    
                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                    
                } else {
                    _conversationArr = nil;
                }
                //            [self.chatTableView reloadData];
            });
        }];
        
    }
}

NSInteger sortType1(id object1,id object2,void *cha) {
    JMSGConversation *model1 = (JMSGConversation *)object1;
    JMSGConversation *model2 = (JMSGConversation *)object2;
    if([model1.latestMessage.timestamp integerValue] > [model2.latestMessage.timestamp integerValue]) {
        return NSOrderedAscending;
    } else if([model1.latestMessage.timestamp integerValue] < [model2.latestMessage.timestamp integerValue]) {
        return NSOrderedDescending;
    }
    return NSOrderedSame;
}
//


#pragma mark --排序conversation
- (NSMutableArray *)sortConversation:(NSMutableArray *)conversationArr {
    NSArray *sortResultArr = [conversationArr sortedArrayUsingFunction:sortType1 context:nil];
    return [NSMutableArray arrayWithArray:sortResultArr];
}



-(void)creatConversation:(CDVInvokedUrlCommand *)command
{
    
    __block JCHATConversationViewController *sendMessageCtl = [[JCHATConversationViewController alloc] init];
    sendMessageCtl.superViewController = self;
    sendMessageCtl.hidesBottomBarWhenPushed = YES;
    //    [[alertView textFieldAtIndex:0] resignFirstResponder];
    __weak __typeof(self)weakSelf = self;
    [JMSGConversation createSingleConversationWithUsername:[command.arguments objectAtIndex:0] appKey:JMESSAGE_APPKEY completionHandler:^(id resultObject, NSError *error) {
        [[JCHATAlertViewWait ins] hidenAll];
        
        if (error == nil) {
            [MBProgressHUD hideAllHUDsForView:self.viewController.view animated:YES];
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            sendMessageCtl.conversation = resultObject;
            UINavigationController *sendMessageNV = [[UINavigationController alloc]initWithRootViewController:sendMessageCtl];
            [sendMessageNV.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, nil]];
            [sendMessageNV.navigationBar setBarTintColor:[UIColor blackColor]];
            
            [strongSelf.viewController presentViewController:sendMessageNV animated:YES completion:nil];
        }
    }];
}


-(void)alertWithTitle:(NSString *)title
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:@"提示" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    
    [alertVC addAction:action];
    
    [self.viewController presentViewController:alertVC animated:YES completion:nil];
    
}

//修改头像和昵称信息
-(void)resetInfo:(CDVInvokedUrlCommand *)command
{
    NSString *infoMessage = [command.arguments objectAtIndex:0];
    NSInteger state = [[command.arguments objectAtIndex:1] integerValue];
    JMSGUser *user = [JMSGUser myInfo];
    if (state == 0) {
        
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:infoMessage]]];
        NSLog(@"头像数据image    urlstr========%@ image =====%@",infoMessage,image);
        [user thumbAvatarData:^(NSData *data, NSString *objectId, NSError *error) {
            if(error == nil) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [JMSGUser updateMyInfoWithParameter:UIImageJPEGRepresentation(image, 1) userFieldType:kJMSGUserFieldsAvatar completionHandler:^(id resultObject, NSError *error) {
                        if (error == nil) {
                            //                            [self alertWithTitle:@"修改头像成功"];
                        }
                    }];
                    
                });
                
            }
            else
            {
                NSLog(@"上传头像错误 =====error = %@",error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [JMSGUser updateMyInfoWithParameter:UIImageJPEGRepresentation(image, 1) userFieldType:kJMSGUserFieldsAvatar completionHandler:^(id resultObject, NSError *error) {
                        if (error == nil) {
                            //                        [self alertWithTitle:@"修改头像成功"];
                        }
                    }];
                    
                });
            }
            
            
        }];
        
        
    }
    else if (state == 1)
    {
        if (![infoMessage isEqualToString:user.nickname]) {
            [JMSGUser updateMyInfoWithParameter:infoMessage userFieldType:kJMSGUserFieldsNickname completionHandler:^(id resultObject, NSError *error) {
                if (error == nil) {
                    [self alertWithTitle:@"修改昵称成功"];
                }
            }];
            
        }
        
        
    }
    
}



@end
